package com.lib724.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UrlFilter implements Filter {
	private Log log = LogFactory.getLog(UrlFilter.class);
	public void destroy() {}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException,
			ServletException {
		String url = ((HttpServletRequest)request).getRequestURI();
		if (isFilterUrl(url)) {
			filter.doFilter(request, response);
		} else {
			url = convertUrl(url, ((HttpServletRequest)request).getQueryString());
			RequestDispatcher dispatcher = request.getRequestDispatcher(url);
			if (dispatcher == null)
				log.warn("Error Current URL:[" + url + "] hasn't a dispatcher!");
			else
				dispatcher.forward(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {}

	public boolean isFilterUrl(final String url) {
		if (url.indexOf(".jsp") > 0)
			return true;
		if (url.indexOf(".htm") > 0)
			return true;
		if (url.indexOf(".html") > 0)
			return true;
		if (url.indexOf(".do") > 0)
			return true;		
		if (url.endsWith(".gif"))
			return true;
		if (url.endsWith(".png"))
			return true;		
		if (url.endsWith(".js"))
			return true;
		if (url.endsWith(".css"))
			return true;
		if (url.endsWith(".swf"))
			return true;		
		return false;
	}
	/**
	 * http://主机名[:端口][/应用名]/模块名/控制器名/函数名.do[?参数名=参数值] 注：方括号代表可省
	 * @param url
	 * @param query TODO
	 * @return
	 */

	private String convertUrl(String url, String query) {
		StringBuilder builder = new StringBuilder();
		int idx = url.indexOf('?');
		if (idx != -1) {
			builder.append(url.substring(0, idx));
			builder.append(".do");
			builder.append(url.substring(idx + 1));
		} else {
			builder.append(url);
			builder.append(".do");
		}
		if (query != null && !"".equals(query.trim())) {
			builder.append("?");
			builder.append(query);
		}
		return builder.toString();
	}
}
